package com.eastdigit.org.controller;

import com.eastdigit.org.model.Department;
import com.eastdigit.org.service.DepartmentService;
import com.eastdigit.servlet.*;
import com.eastdigit.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @RequestMapping(value = "/add")
    @ResponseBody
    @DeptOptPermValidate(id = "deptId", deptId = "parentDeptId")
    public JSONObject add(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        departmentService.addDepartment(getDepartment(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    @DeptOptPermValidate(id = "deptId", deptId = "deptId", isUpdate = true)
    public JSONObject update(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        departmentService.updateDepartment(getDepartment(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    @DeptOptPermValidate(id = "deptId", deptId = "deptId")
    public JSONObject remove(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        departmentService.deleteDepartment(reqBean.getInfo("deptId"));
        return Response.responseSuccess();
    }

    /**
     * 获取指定部门
     * 
     * @param reqBean
     * @return
     */
    private Department getDepartment(ReqBean reqBean) {
        Department department = new Department();
        if (StringUtil.isNotEmpty(reqBean.getInfo("deptId"))) {
            department.setId(reqBean.getInfo("deptId"));
        }
        department.setParentId(reqBean.getInfo("parentDeptId"));
        department.setCode(reqBean.getInfo("deptCode"));
        department.setName(reqBean.getInfo("deptName"));
        department.setShortName(reqBean.getInfo("shortName"));
        department.setType(reqBean.getInfo("deptType"));
        department.setOperator(reqBean.getUserId());
        department.setRemark(reqBean.getInfo("remark"));
        return department;
    }
}
